package com.lagou.client;

import com.lagou.protocol.RpcRequest;
import com.lagou.protocol.RpcResponse;
import io.netty.channel.Channel;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ClientRequestHandler implements Callable<String> {

    private RpcRequest rpcRequest; // 发送的消息
    private ConcurrentHashMap<String, RpcResponse> resultMap; // 结果池
    private Channel channel; // 通道
    // 选好的通道

    public ClientRequestHandler(ConcurrentHashMap<String, RpcResponse> resultMap, Channel channel) {
        this.channel = channel;
        this.resultMap = resultMap;
    }

    /**
     * 写出数据
     */
    public void setRequest(RpcRequest rpcRequest) {
        this.rpcRequest = rpcRequest;
    }

    public String call() throws InterruptedException {
        String name = Thread.currentThread().getName();
        RpcResponse rpcResponse = new RpcResponse();
        CountDownLatch latch = new CountDownLatch(1);
        rpcResponse.setLatch(latch);
        rpcRequest.setThreadInfo(name);
        channel.writeAndFlush(rpcRequest);
        resultMap.put(name, rpcResponse);
        latch.await(3, TimeUnit.SECONDS);
        resultMap.remove(name);
        return rpcResponse.getResult();
    }
}
